from PySide6.QtWidgets import (QDialog, QVBoxLayout, QLabel, QPushButton,
                               QHBoxLayout, QLineEdit, QTextEdit, QMessageBox,
                               QWidget, QFormLayout, QGroupBox, QSplitter,
                               QTabWidget, QScrollArea, QTableWidget,
                               QTableWidgetItem, QHeaderView, QApplication,
                               QFileDialog)
from terminal.ui import Terminal
from terminal.tabs import TabManager
from PySide6.QtCore import Qt
import re

class TemplateGenerateDialog(QDialog):
    def __init__(self, template, parent=None):
        super().__init__(parent)
        self.template = template
        self.variables = []
        self.loops = []
        self.sub_table_data = {}  # 用于存储子表格数据
        self._loading_subtable = False  # 添加标记，用于防止重复渲染
        self.init_ui()
        self.parse_variables()
        self.create_variable_inputs()
        self.update_preview()

    def add_table_row(self, table):
        current_row = table.rowCount()
        table.insertRow(current_row)
        
        # 检查是否是子表格，如果是则更新子表数据缓存
        table_name = table.objectName()
        if '_sub_' in table_name:
            # 解析表名获取loop_id和sub_loop_description
            parts = table_name.split('_sub_')
            if len(parts) == 2:
                loop_id = parts[0]
                sub_desc = parts[1]
                # 确保使用一致的键名格式，去掉可能的'table_'前缀
                if loop_id.startswith('table_'):
                    loop_id = loop_id[6:]
                table_key = f"{loop_id}_{sub_desc}"
                
                # 获取外键值（父行ID）
                if table.rowCount() > 0 and table.item(current_row-1, table.columnCount()-1):
                    parent_row_id = int(table.item(current_row-1, table.columnCount()-1).text())
                    
                    # 设置新行的外键值
                    item = QTableWidgetItem(str(parent_row_id))
                    table.setItem(current_row, table.columnCount()-1, item)
                    
                    # 确保子表数据缓存中有该父行的条目
                    if table_key not in self.sub_table_data:
                        self.sub_table_data[table_key] = {}
                    if parent_row_id not in self.sub_table_data[table_key]:
                        self.sub_table_data[table_key][parent_row_id] = []
                    
                    # 为子表的新行添加数据，自动引用主表中的变量值
                    row_data = [''] * (table.columnCount() - 1)
                    
                    # 获取主表和主表行号
                    main_table_name = loop_id
                    main_table = self.findChild(QTableWidget, f"table_{main_table_name}")
                    
                    if main_table:
                        # 获取主表和子表的变量定义
                        # 查找主循环定义
                        for loop in self.loops:
                            if str(loop['id']) == main_table_name or f"table_{loop['id']}" == main_table_name:
                                main_vars = loop['vars']
                                # 查找子循环定义
                                for sub_loop in loop['children']:
                                    if sub_loop['description'] == sub_desc:
                                        sub_vars = sub_loop['vars']
                                        
                                        # 查找变量名相同的列，并自动填充值
                                        for sub_col, sub_var in enumerate(sub_vars):
                                            sub_var_name = sub_var['name']
                                            # 在主表变量中查找相同名称的变量
                                            for main_col, main_var in enumerate(main_vars):
                                                if main_var['name'] == sub_var_name:
                                                    # 获取主表中该变量的值
                                                    main_item = main_table.item(parent_row_id, main_col)
                                                    if main_item and main_item.text().strip():
                                                        # 将主表中的值填充到子表中
                                                        row_data[sub_col] = main_item.text()
                                                        # 同时更新表格UI
                                                        item = QTableWidgetItem(main_item.text())
                                                        table.setItem(current_row, sub_col, item)
                                                    break
                                        break
                                break
                    
                    self.sub_table_data[table_key][parent_row_id].append(row_data)
        
        self.update_preview()

    def delete_table_row(self, table):
        current_row = table.currentRow()
        if current_row >= 0 and table.rowCount() > 1:
            # 检查是否是子表格，如果是则更新子表数据缓存
            table_name = table.objectName()
            if '_sub_' in table_name:
                # 解析表名获取loop_id和sub_loop_description
                parts = table_name.split('_sub_')
                if len(parts) == 2:
                    loop_id = parts[0]
                    sub_desc = parts[1]
                    # 确保使用一致的键名格式，去掉可能的'table_'前缀
                    if loop_id.startswith('table_'):
                        loop_id = loop_id[6:]
                    table_key = f"{loop_id}_{sub_desc}"
                    
                    # 获取外键值（父行ID）
                    if table.item(current_row, table.columnCount()-1):
                        parent_row_id = int(table.item(current_row, table.columnCount()-1).text())
                        
                        # 如果缓存中存在该父行的数据，则更新缓存
                        if table_key in self.sub_table_data and parent_row_id in self.sub_table_data[table_key]:
                            # 从缓存中删除对应行的数据
                            if len(self.sub_table_data[table_key][parent_row_id]) > current_row:
                                self.sub_table_data[table_key][parent_row_id].pop(current_row)
            
            table.removeRow(current_row)
            self.update_preview()

    def update_preview(self):
        # 如果正在加载子表格数据，不更新预览
        if hasattr(self, '_loading_subtable') and self._loading_subtable:
            return
        
        # 清除所有子循环内容已添加的标记
        for attr in list(self.__dict__.keys()):
            if attr.startswith('__sub_loop_') and attr.endswith('_added__'):
                delattr(self, attr)
            
        content = self.template['content']
        lines = content.split('\n')
        result_lines = []
    
        
        i = 0
        while i < len(lines):
            line = lines[i]
            
            # 检查是否是循环块开始
            loop_match = re.match(r'\[FOR\|([^\]]+)\]', line)
            if loop_match:
                loop_desc = loop_match.group(1)
                loop_lines = []
                loop_content = []
                i += 1
                
                # 收集循环块内容，包括子循环标记
                start_i = i
                while i < len(lines) and '[ENDFOR]' not in lines[i]:
                    loop_lines.append(lines[i])
                    i += 1
                
                # 获取循环块的表格
                for loop in self.loops:
                    if loop['description'] == loop_desc:
                        table = self.findChild(QTableWidget, f"table_{loop['id']}")
                        if table:
                            # 预处理子循环块
                            sub_loop_blocks = {}
                            current_sub_loop = None
                            sub_loop_content = []
                            
                            # 先收集所有子循环块
                            temp_i = 0
                            while temp_i < len(loop_lines):
                                loop_line = loop_lines[temp_i]
                                # 检查是否是子循环开始
                                sub_start_match = re.match(r'\[SUBFOR\|([^\]]+)\]', loop_line)
                                if sub_start_match:
                                    current_sub_loop = sub_start_match.group(1)
                                    sub_loop_content = []
                                    temp_i += 1
                                    continue
                                
                                # 检查是否是子循环结束
                                if '[ENDSUBFOR]' in loop_line:
                                    if current_sub_loop:
                                        sub_loop_blocks[current_sub_loop] = sub_loop_content
                                        current_sub_loop = None
                                    temp_i += 1
                                    continue
                                
                                # 收集子循环内容
                                if current_sub_loop:
                                    sub_loop_content.append(loop_line)
                                temp_i += 1
                            
                            # 处理每一行数据
                            for row in range(table.rowCount()):
                                # 为每行创建一个新的内容副本
                                row_content = []
                                
                                # 处理主循环内容，跳过子循环块
                                temp_i = 0
                                while temp_i < len(loop_lines):
                                    loop_line = loop_lines[temp_i]
                                    
                                    # 跳过子循环块
                                    if re.match(r'\[SUBFOR\|([^\]]+)\]', loop_line):
                                        # 跳过子循环块直到ENDSUBFOR
                                        while temp_i < len(loop_lines) and '[ENDSUBFOR]' not in loop_lines[temp_i]:
                                            temp_i += 1
                                        temp_i += 1  # 跳过ENDSUBFOR
                                        continue
                                    
                                    # 跳过ENDSUBFOR行
                                    if '[ENDSUBFOR]' in loop_line:
                                        temp_i += 1
                                        continue
                                    
                                    # 处理主循环变量
                                    processed_line = loop_line
                                    skip_line = False
                                    for col, var in enumerate(loop['vars']):
                                        item = table.item(row, col)
                                        value = item.text() if item else ''
                                        var_pattern = f"{{{var['name']}|{var['description']}}}" 
                                        if value:
                                            # 检查是否为特殊符号%，如果是则标记跳过该行
                                            if value == '%' and var_pattern in processed_line:
                                                skip_line = True
                                                break
                                            processed_line = processed_line.replace(var_pattern, value)
                                        else:
                                            processed_line = processed_line.replace(var_pattern, f"{{{var['name']}}}")                                    
                                    # 如果不需要跳过该行，则添加到内容中
                                    if not skip_line:
                                        row_content.append(processed_line)
                                    temp_i += 1
                                
                                # 处理子循环
                                if 'children' in loop and loop['children']:
                                    for sub_loop in loop['children']:
                                        if sub_loop['description'] not in sub_loop_blocks:
                                            continue
                                            
                                        sub_table = self.findChild(QTableWidget, f"table_{loop['id']}_sub_{sub_loop['description']}")
                                        if not sub_table:
                                            continue
                                            
                                        # 获取当前主表行对应的子表数据
                                        # 确保使用一致的键名格式
                                        loop_id = loop['id']
                                        if isinstance(loop_id, str) and loop_id.startswith('table_'):
                                            loop_id = loop_id[6:]
                                        table_key = f"{loop_id}_{sub_loop['description']}"
                                        sub_loop_template = sub_loop_blocks[sub_loop['description']]
                                        
                                        # 处理子表数据
                                        sub_rows_content = []
                                        has_valid_data = False
                                        
                                        # 优先使用缓存数据
                                        if (hasattr(self, 'sub_table_data') and 
                                            table_key in self.sub_table_data and 
                                            row in self.sub_table_data[table_key]):
                                            
                                            for sub_row_data in self.sub_table_data[table_key][row]:
                                                print(f"使用缓存数据：{self.sub_table_data[table_key][row]}")
                                                # 检查该行是否有实际数据
                                                if not any(value.strip() for value in sub_row_data):
                                                    continue
                                                    
                                                has_valid_data = True
                                                sub_row_content = sub_loop_template.copy()
                                                
                                                # 替换子循环变量
                                                skip_sub_row = False
                                                for sub_col, sub_var in enumerate(sub_loop['vars']):
                                                    sub_value = sub_row_data[sub_col] if sub_col < len(sub_row_data) else ''
                                                    sub_var_pattern = f"{{{sub_var['name']}|{sub_var['description']}}}" 
                                                    
                                                    if sub_value:
                                                        # 检查是否为特殊符号%，如果是则标记跳过该行
                                                        if sub_value == '%' and sub_var_pattern in ''.join(sub_row_content):
                                                            # 只跳过包含该变量的行，而不是整个子循环
                                                            sub_row_content = [line for line in sub_row_content if sub_var_pattern not in line]
                                                        else:
                                                            sub_row_content = [sub_line.replace(sub_var_pattern, sub_value) 
                                                                          for sub_line in sub_row_content]
                                                    else:
                                                        sub_row_content = [sub_line.replace(sub_var_pattern, f"{{{sub_var['name']}}}")
                                                                          for sub_line in sub_row_content]
                                                
                                                # 不再使用skip_sub_row来决定是否添加内容
                                                sub_rows_content.extend(sub_row_content)
                                        else:
                                            # 如果没有缓存数据，从表格中读取
                                            for sub_row in range(sub_table.rowCount()):
                                                print(f"使用表格数据：{sub_row}")
                                                # 检查外键值是否匹配当前主表行
                                                parent_item = sub_table.item(sub_row, sub_table.columnCount() - 1)
                                                parent_row = int(parent_item.text()) if parent_item else -1
                                                
                                                if parent_row != row:
                                                    continue
                                                
                                                # 检查该行是否有实际数据
                                                row_has_data = False
                                                sub_row_values = []
                                                # 不再使用skip_sub_row标记整行跳过
                                                has_percent_vars = []
                                                
                                                for sub_col in range(sub_table.columnCount() - 1):
                                                    sub_item = sub_table.item(sub_row, sub_col)
                                                    sub_value = sub_item.text() if sub_item else ''
                                                    sub_row_values.append(sub_value)
                                                    if sub_value.strip():
                                                        row_has_data = True
                                                    # 检查是否为特殊符号%，记录包含%的变量索引
                                                    if sub_value == '%':
                                                        has_percent_vars.append(sub_col)
                                                
                                                if not row_has_data:
                                                    continue
                                                    
                                                has_valid_data = True
                                                sub_row_content = sub_loop_template.copy()
                                                
                                                # 替换子循环变量
                                                for sub_col, sub_var in enumerate(sub_loop['vars']):
                                                    if sub_col >= len(sub_row_values):
                                                        continue
                                                        
                                                    sub_value = sub_row_values[sub_col]
                                                    sub_var_pattern = f"{{{sub_var['name']}|{sub_var['description']}}}" 
                                                    
                                                    if sub_value and sub_value != '%':
                                                        sub_row_content = [sub_line.replace(sub_var_pattern, sub_value) 
                                                                          for sub_line in sub_row_content]
                                                    elif sub_value == '%':
                                                        # 只过滤掉包含该变量的行
                                                        sub_row_content = [line for line in sub_row_content if sub_var_pattern not in line]
                                                    else:
                                                        sub_row_content = [sub_line.replace(sub_var_pattern, f"{{{sub_var['name']}}}")
                                                                          for sub_line in sub_row_content]
                                                
                                                # 不再使用skip_sub_row来决定是否添加内容
                                                sub_rows_content.extend(sub_row_content)
                                        
                                        # 始终添加子表内容，即使没有实际数据也显示变量名
                                        # 如果没有有效数据，则添加带变量名的模板内容
                                        if not has_valid_data:
                                            # 创建一个空行，显示变量名
                                            sub_row_content = sub_loop_template.copy()
                                            
                                            # 替换所有变量为变量名格式
                                            for sub_var in sub_loop['vars']:
                                                sub_var_pattern = f"{{{sub_var['name']}|{sub_var['description']}}}" 
                                                sub_row_content = [sub_line.replace(sub_var_pattern, f"{{{sub_var['name']}}}") 
                                                              for sub_line in sub_row_content]
                                            
                                            sub_rows_content.extend(sub_row_content)
                                        # 找到子循环标记在主循环中的位置
                                        sub_loop_marker = f"[SUBFOR|{sub_loop['description']}]"
                                        sub_loop_end_marker = "[ENDSUBFOR]"
                                        
                                        # 在主循环内容中查找子循环标记的位置
                                        marker_positions = []
                                        for pos, line in enumerate(loop_lines):
                                            if sub_loop_marker in line:
                                                start_pos = pos
                                                marker_positions.append(start_pos)
                                            elif sub_loop_end_marker in line and marker_positions:
                                                end_pos = pos
                                                marker_positions.append(end_pos)
                                                break
                                        
                                        # 如果找到了子循环标记的位置，在对应位置插入子循环内容
                                        if len(marker_positions) == 2:
                                            # 计算子循环在当前行内容中的插入位置
                                            insert_pos = 0
                                            for pos in range(marker_positions[0]):
                                                if pos < temp_i and '[SUBFOR|' not in loop_lines[pos] and '[ENDSUBFOR]' not in loop_lines[pos]:
                                                    insert_pos += 1
                                            
                                            # 在适当的位置插入子循环内容
                                            if insert_pos <= len(row_content):
                                                row_content[insert_pos:insert_pos] = sub_rows_content
                                            else:
                                                # 如果计算的位置超出了行内容长度，则添加到末尾
                                                row_content.extend(sub_rows_content)
                                        else:
                                            # 如果没有找到标记位置，则添加到行内容末尾
                                            row_content.extend(sub_rows_content)
                                
                                # 将当前行的内容添加到循环内容中
                                loop_content.extend(row_content)
                
                # 将处理好的循环内容添加到结果中
                result_lines.extend(loop_content)
                i += 1  # 跳过 [ENDFOR]
            else:
                # 处理普通变量
                processed_line = line
                skip_line = False
                for var in self.variables:
                    var_pattern = f"{{{var['name']}|{var['description']}}}" 
                    input_field = self.findChild(QLineEdit, f"var_{var['id']}")
                    if input_field:
                        value = input_field.text().strip()
                        if value:
                            # 检查是否为特殊符号%，如果是则标记跳过该行
                            if value == '%' and var_pattern in processed_line:
                                skip_line = True
                                break
                            processed_line = processed_line.replace(var_pattern, value)
                        else:
                            processed_line = processed_line.replace(var_pattern, f"{{{var['name']}}}")                
                # 跳过[ENDFOR]和[ENDSUBFOR]标记行以及被标记为跳过的行
                if '[ENDFOR]' not in processed_line and '[ENDSUBFOR]' not in processed_line and '[SUBFOR|' not in processed_line and not skip_line:
                    result_lines.append(processed_line)
                i += 1
        
        self.preview_text.setText('\n'.join(result_lines))

    def create_variable_inputs(self):
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_widget = QWidget()
        scroll_area.setWidget(scroll_widget)
        form_layout = QFormLayout(scroll_widget)
        
        # 创建按钮布局
        btn_layout = QHBoxLayout()
        
        # 处理普通变量
        for var in self.variables:
            if isinstance(var, dict) and 'id' in var:
                input_field = QLineEdit()
                input_field.setObjectName(f"var_{var['id']}")
                input_field.textChanged.connect(self.update_preview)
                form_layout.addRow(f"{var['description']}：", input_field)
        
        # 处理循环块
        for loop in self.loops:
            group_box = QGroupBox(loop['description'])
            group_layout = QVBoxLayout(group_box)
            table = QTableWidget()
            table.setObjectName(f"table_{loop['id']}")
            table.setColumnCount(len(loop['vars']))
            # 默认增加一个空行
            table.insertRow(0)
            headers = [var['description'] for var in loop['vars']]
            table.setHorizontalHeaderLabels(headers)
            
            # 设置表格列宽自适应
            header = table.horizontalHeader()
            for i in range(len(headers)):
                header.setSectionResizeMode(i, QHeaderView.ResizeMode.Stretch)
            
            # 添加行的按钮
            btn_layout = QHBoxLayout()
            add_row_btn = QPushButton('添加行')
            add_row_btn.clicked.connect(lambda checked, t=table: self.add_table_row(t))
            delete_row_btn = QPushButton('删除行')
            delete_row_btn.clicked.connect(lambda checked, t=table: self.delete_table_row(t))
            btn_layout.addWidget(add_row_btn)
            btn_layout.addWidget(delete_row_btn)
            btn_layout.addStretch()
            
            group_layout.addWidget(table)
            group_layout.addLayout(btn_layout)
            
            # 连接单元格变化信号
            table.itemChanged.connect(lambda item, t=table, l=loop: self.on_main_table_data_changed(item, t, l))
            # 连接行点击事件
            table.itemSelectionChanged.connect(lambda t=table, l=loop: self.on_main_table_row_selected(t, l))
            
            # 创建子循环表格
            if 'children' in loop and loop['children']:
                for sub_loop in loop['children']:
                    sub_group = QGroupBox(sub_loop['description'])
                    sub_group.setObjectName(f"sub_group_{loop['id']}_{sub_loop['description']}")
                    sub_layout = QVBoxLayout(sub_group)
                    
                    sub_table = QTableWidget()
                    sub_table.setObjectName(f"table_{loop['id']}_sub_{sub_loop['description']}")
                    # 增加一列用于存储外键
                    sub_table.setColumnCount(len(sub_loop['vars']) + 1)
                    sub_headers = [var['description'] for var in sub_loop['vars']]
                    sub_headers.append('parent_row_id')
                    sub_table.setHorizontalHeaderLabels(sub_headers)
                    
                    # 设置子表格列宽自适应，并隐藏外键列
                    sub_header = sub_table.horizontalHeader()
                    for i in range(len(sub_headers) - 1):
                        sub_header.setSectionResizeMode(i, QHeaderView.ResizeMode.Stretch)
                    sub_table.hideColumn(len(sub_headers) - 1)
                    
                    # 子循环的添加/删除行按钮
                    sub_btn_layout = QHBoxLayout()
                    sub_add_btn = QPushButton('添加行')
                    sub_add_btn.clicked.connect(lambda checked, t=sub_table: self.add_table_row(t))
                    sub_delete_btn = QPushButton('删除行')
                    sub_delete_btn.clicked.connect(lambda checked, t=sub_table: self.delete_table_row(t))
                    sub_btn_layout.addWidget(sub_add_btn)
                    sub_btn_layout.addWidget(sub_delete_btn)
                    sub_btn_layout.addStretch()
                    
                    sub_layout.addWidget(sub_table)
                    sub_layout.addLayout(sub_btn_layout)
                    
                    # 连接子表格单元格变化信号 - 修改这里，连接到专门处理子表格数据变化的方法
                    sub_table.itemChanged.connect(self.on_sub_table_data_changed)
                    
                    group_layout.addWidget(sub_group)
            
            form_layout.addRow(group_box)
        
        # 将滚动区域添加到左侧布局
        self.left_layout.addWidget(scroll_area)
        self.left_layout.addLayout(btn_layout)

    def on_sub_table_data_changed(self, item):
        # 获取子表格
        table = self.sender()
        if not table:
            return
            
        # 获取表名和行号
        table_name = table.objectName()
        row = item.row()
        col = item.column()
        
        # 确保是子表格
        if '_sub_' in table_name:
            # 解析表名获取loop_id和sub_loop_description
            parts = table_name.split('_sub_')
            if len(parts) == 2:
                loop_id = parts[0]
                sub_desc = parts[1]
                # 确保使用一致的键名格式，去掉可能的'table_'前缀
                if loop_id.startswith('table_'):
                    loop_id = loop_id[6:]
                table_key = f"{loop_id}_{sub_desc}"
                
                # 获取外键值（父行ID）
                if table.item(row, table.columnCount()-1):
                    parent_row_id = int(table.item(row, table.columnCount()-1).text())
                    
                    # 确保子表数据缓存中有该父行的条目
                    if table_key not in self.sub_table_data:
                        self.sub_table_data[table_key] = {}
                    if parent_row_id not in self.sub_table_data[table_key]:
                        self.sub_table_data[table_key][parent_row_id] = []
                    
                    # 更新缓存中的数据
                    # 确保有足够的行
                    while len(self.sub_table_data[table_key][parent_row_id]) <= row:
                        self.sub_table_data[table_key][parent_row_id].append([''] * (table.columnCount() - 1))
                    
                    # 更新单元格数据
                    if col < table.columnCount() - 1:  # 不处理外键列
                        self.sub_table_data[table_key][parent_row_id][row][col] = item.text()
                        
                        # 确保更新后的数据能够在预览中正确显示
                        # 重新保存整行数据，确保数据一致性
                        row_data = []
                        for c in range(table.columnCount() - 1):  # 不包括外键列
                            cell_item = table.item(row, c)
                            row_data.append(cell_item.text() if cell_item else '')
                        self.sub_table_data[table_key][parent_row_id][row] = row_data
                        print(f"保存子表格数据：{row_data}, 子表格缓存数据：{self.sub_table_data}, 是否正在加载子表格数据：{self._loading_subtable}")
        
        # 更新预览
        self.update_preview()
    
    def on_main_table_data_changed(self, item, table, loop):
        # 获取变更的行号和列号
        row = item.row()
        col = item.column()
        value = item.text()
        
        # 获取当前变更的变量名
        if col < len(loop['vars']):
            current_var_name = loop['vars'][col]['name']
            
            # 检查是否有子表格
            if 'children' in loop and loop['children']:
                for sub_loop in loop['children']:
                    sub_table = self.findChild(QTableWidget, f"table_{loop['id']}_sub_{sub_loop['description']}")
                    if not sub_table:
                        continue
                    
                    # 查找子表中是否有相同名称的变量
                    for sub_col, sub_var in enumerate(sub_loop['vars']):
                        if sub_var['name'] == current_var_name:
                            # 找到相同名称的变量，更新子表中对应行的值
                            # 获取子表中与当前主表行关联的所有行
                            for sub_row in range(sub_table.rowCount()):
                                # 检查外键值是否匹配当前主表行
                                parent_item = sub_table.item(sub_row, sub_table.columnCount() - 1)
                                if parent_item and int(parent_item.text()) == row:
                                    # 更新子表中对应的值
                                    sub_table.blockSignals(True)  # 阻止信号触发循环更新
                                    sub_table.setItem(sub_row, sub_col, QTableWidgetItem(value))
                                    sub_table.blockSignals(False)
                                    
                                    # 同时更新缓存数据
                                    loop_id = loop['id']
                                    if isinstance(loop_id, str) and loop_id.startswith('table_'):
                                        loop_id = loop_id[6:]
                                    table_key = f"{loop_id}_{sub_loop['description']}"
                                    
                                    if table_key in self.sub_table_data and row in self.sub_table_data[table_key]:
                                        if sub_row < len(self.sub_table_data[table_key][row]):
                                            self.sub_table_data[table_key][row][sub_row][sub_col] = value
                            break
        
        # 更新预览
        self.update_preview()
    
    def on_main_table_row_selected(self, table, loop):
        # 获取当前行号
        current_row = table.currentRow()
        if current_row < 0:
            return
        
        # 标记正在加载子表格数据，防止触发不必要的预览更新
        self._loading_subtable = True
        
        # 显示对应的子表格并更新外键
        if 'children' in loop and loop['children']:
            for sub_loop in loop['children']:
                sub_group = self.findChild(QGroupBox, f"sub_group_{loop['id']}_{sub_loop['description']}")
                sub_table = self.findChild(QTableWidget, f"table_{loop['id']}_sub_{sub_loop['description']}")
                if sub_group and sub_table:
                    # 保存当前子表格的数据到缓存
                    # 确保使用一致的键名格式
                    loop_id = loop['id']
                    if isinstance(loop_id, str) and loop_id.startswith('table_'):
                        loop_id = loop_id[6:]
                    table_key = f"{loop_id}_{sub_loop['description']}"
                    if table_key not in self.sub_table_data:
                        self.sub_table_data[table_key] = {}
                    
                    # 获取当前显示的子表格行的外键值
                    current_parent_row = None
                    if sub_table.rowCount() > 0 and sub_table.item(0, sub_table.columnCount() - 1):
                        current_parent_row = int(sub_table.item(0, sub_table.columnCount() - 1).text())
                    
                    # 如果当前显示的是有效数据，保存它
                    if current_parent_row is not None:
                        # 保存当前显示的所有行数据
                        # 先清除该行之前的数据
                        self.sub_table_data[table_key][current_parent_row] = []
                        
                        for row in range(sub_table.rowCount()):
                            row_data = []
                            for col in range(sub_table.columnCount() - 1):  # 不包括外键列
                                item = sub_table.item(row, col)
                                row_data.append(item.text() if item else '')
                            # 保存所有行数据，包括空行
                            self.sub_table_data[table_key][current_parent_row].append(row_data)
                    
                    # 清空子表格
                    sub_table.setRowCount(0)
                    
                    # 加载当前行的数据
                    if current_row in self.sub_table_data[table_key] and self.sub_table_data[table_key][current_row]:
                        for row_data in self.sub_table_data[table_key][current_row]:
                            row = sub_table.rowCount()
                            sub_table.insertRow(row)
                            for col, value in enumerate(row_data):
                                item = QTableWidgetItem(value)
                                sub_table.setItem(row, col, item)
                            # 设置外键值
                            item = QTableWidgetItem(str(current_row))
                            sub_table.setItem(row, sub_table.columnCount() - 1, item)
                    else:
                        # 如果没有数据，添加一个空行，方便用户输入
                        row = sub_table.rowCount()
                        sub_table.insertRow(row)
                        # 设置外键值
                        item = QTableWidgetItem(str(current_row))
                        sub_table.setItem(row, sub_table.columnCount() - 1, item)
                        
                        # 自动引用主表中的变量值
                        # 获取主表中当前行的数据
                        main_table = table
                        main_row = current_row
                        
                        # 获取主表和子表的变量定义
                        main_vars = loop['vars']
                        sub_vars = sub_loop['vars']
                        
                        # 查找变量名相同的列，并自动填充值
                        for sub_col, sub_var in enumerate(sub_vars):
                            sub_var_name = sub_var['name']
                            # 在主表变量中查找相同名称的变量
                            for main_col, main_var in enumerate(main_vars):
                                if main_var['name'] == sub_var_name:
                                    # 获取主表中该变量的值
                                    main_item = main_table.item(main_row, main_col)
                                    if main_item and main_item.text().strip():
                                        # 将主表中的值填充到子表中
                                        sub_item = QTableWidgetItem(main_item.text())
                                        sub_table.setItem(row, sub_col, sub_item)
                                        
                                        # 同时更新缓存数据
                                        if table_key not in self.sub_table_data:
                                            self.sub_table_data[table_key] = {}
                                        if current_row not in self.sub_table_data[table_key]:
                                            self.sub_table_data[table_key][current_row] = []
                                        while len(self.sub_table_data[table_key][current_row]) <= row:
                                            self.sub_table_data[table_key][current_row].append([''] * (sub_table.columnCount() - 1))
                                        self.sub_table_data[table_key][current_row][row][sub_col] = main_item.text()
                                    break
        
        # 重置加载标记
        self._loading_subtable = False
        # 更新预览，确保子表数据能够正确显示
        self.update_preview()

    def init_ui(self):
        # 创建主布局
        layout = QHBoxLayout(self)
        layout.setSpacing(16)
        
        # 左侧参数填写区域
        left_container = QWidget()
        left_container.setMinimumWidth(400)
        self.left_layout = QVBoxLayout(left_container)
        
        # 按钮
        btn_layout = QHBoxLayout()
        generate_btn = QPushButton('导出至文件')
        generate_btn.clicked.connect(self.export_to_file)
        export_btn = QPushButton('导出至终端')
        export_btn.clicked.connect(self.export_to_terminal)
        cancel_btn = QPushButton('取消')
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(generate_btn)
        btn_layout.addWidget(export_btn)
        btn_layout.addWidget(cancel_btn)
        self.left_layout.addLayout(btn_layout)
        
        # 右侧预览区域
        right_container = QWidget()
        right_container.setMinimumWidth(400)
        right_layout = QVBoxLayout(right_container)
        
        preview_label = QLabel('实时预览：')
        self.preview_text = QTextEdit()
        self.preview_text.setReadOnly(True)
        right_layout.addWidget(preview_label)
        right_layout.addWidget(self.preview_text)
        
        # 添加分隔线
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.addWidget(left_container)
        splitter.addWidget(right_container)
        layout.addWidget(splitter)
        
        self.setWindowTitle('配置生成')
        self.resize(1200, 800)
    
    def parse_variables(self):
        """解析模板中的变量"""
        content = self.template['content']
        var_id = 0
        loop_id = 0
        sub_loop_id = 0
        
        # 解析普通变量
        normal_vars = re.finditer(r'\{([^}]+)\}', content)
        for match in normal_vars:
            var_parts = match.group(1).split('|')
            if len(var_parts) == 2:  # 变量名|描述
                name, desc = var_parts
                # 检查是否已经添加过该变量
                if not any(var['name'] == name and var['description'] == desc for var in self.variables):
                    # 检查变量是否在循环块内
                    is_in_loop = False
                    try:
                        # 使用更精确的正则表达式匹配循环块
                        for loop_match in re.finditer(r'\[FOR\|([^\[\]]+)\]([\s\S]*?)\[ENDFOR\]', content):
                            # 验证匹配结果
                            if not loop_match or len(loop_match.groups()) != 2:
                                print(f"警告：发现无效的循环块格式")
                                continue
                            if match.start() > loop_match.start() and match.start() < loop_match.end():
                                is_in_loop = True
                                break
                    except Exception as e:
                        print(f"检查变量是否在循环块内时出错: {str(e)}")
                    
                    if not is_in_loop:
                        self.variables.append({
                            'id': f"var_{var_id}",
                            'name': name,
                            'description': desc
                        })
                        var_id += 1
        
        # 解析循环块
        loop_matches = re.finditer(r'\[FOR\|([^\]]+)\]([\s\S]*?)\[ENDFOR\]', content)
        for match in loop_matches:
            loop_desc = match.group(1).strip()  # 提取并清理循环体描述
            loop_content = match.group(2)
            
            # 解析循环块中的变量和子循环
            loop_vars = []
            sub_loops = []
            
            # 解析子循环块
            sub_loop_matches = re.finditer(r'\[SUBFOR\|([^\]]+)\]([\s\S]*?)\[ENDSUBFOR\]', loop_content, re.MULTILINE)
            try:
                for sub_match in sub_loop_matches:
                    if not sub_match or len(sub_match.groups()) != 2:
                        print(f"警告：子循环块格式无效")
                        continue
                        
                    sub_desc = sub_match.group(1).strip()  # 提取并清理子循环体描述
                    sub_content = sub_match.group(2)
                    
                    if not sub_desc or not sub_content:
                        print(f"警告：子循环块描述或内容为空")
                        continue
                    
                    # 解析子循环中的变量
                    sub_vars = []
                    sub_var_matches = re.finditer(r'\{([^}]+)\}', sub_content)
                    
                    # 用于跟踪已添加的变量名
                    added_var_names = set()
                    
                    for var_match in sub_var_matches:
                        var_parts = var_match.group(1).split('|')
                        if len(var_parts) == 2:  # 变量名|描述
                            name, desc = var_parts
                            name = name.strip()
                            desc = desc.strip()
                            if name and desc:  # 确保变量名和描述不为空
                                # 检查变量名是否已存在，如果存在则跳过
                                if name not in added_var_names:
                                    sub_vars.append({
                                        'name': name,
                                        'description': desc
                                    })
                                    added_var_names.add(name)
                            else:
                                print(f"警告：子循环变量格式无效 - {var_match.group(0)}")
                    
                    if sub_vars:  # 只有在有有效变量时才添加子循环
                        sub_loops.append({
                            'type': 'sub_loop',
                            'description': sub_desc,
                            'vars': sub_vars
                        })
                    else:
                        print(f"警告：子循环 '{sub_desc}' 中未找到有效变量")
            except Exception as e:
                print(f"解析子循环时出错: {str(e)}")
                
            # 解析主循环中的变量
            main_var_matches = re.finditer(r'\{([^}]+)\}', re.sub(r'\[SUBFOR\|[^\]]+\][\s\S]*?\[ENDSUBFOR\]', '', loop_content))
            # 用于跟踪已添加的变量名
            added_main_var_names = set()
            
            for var_match in main_var_matches:
                var_parts = var_match.group(1).split('|')
                if len(var_parts) == 2:  # 变量名|描述
                    name, desc = var_parts
                    name = name.strip()
                    desc = desc.strip()
                    if name and desc and name not in added_main_var_names:  # 检查变量名是否已存在
                        loop_vars.append({
                            'name': name,
                            'description': desc
                        })
                        added_main_var_names.add(name)
            
            # 添加循环块到列表
            self.loops.append({
                'id': f"loop_{loop_id}",
                'description': loop_desc,
                'vars': loop_vars,
                'children': sub_loops
            })
            loop_id += 1
        print(f"self.variables: {self.variables}")
        print(f"self.loops: {self.loops}")

    def print_widget_tree(self, widget, level=0):
        """递归打印组件树"""
        indent = '  ' * level
        print(f"{indent}└─ {widget.__class__.__name__} (name: {widget.objectName()})")
        for child in widget.children():
            self.print_widget_tree(child, level + 1)

    def export_to_terminal(self):
        """导出预览内容到当前活动的终端会话"""
        # 获取主窗口实例
        main_window = None
        # 首先尝试通过parent()获取父窗口
        parent = self.parent()
        while parent:
            if parent.objectName() == "main_splitter":
                main_window = parent.window()
                break
            parent = parent.parent()
        # self.print_widget_tree(parent)    
        
        # 如果通过父窗口链没有找到，则尝试从顶层窗口中查找
        if not main_window:
            for widget in QApplication.topLevelWidgets():
                if widget.objectName() == "central_widget":
                    main_window = widget.window()
                    break
                    
        if not main_window:
            return
            
        # 获取当前活动的终端标签页管理器
        tab_manager = None
        center_container = main_window.findChild(QWidget, "center_container")
        if center_container:
            tab_manager = center_container.findChild(TabManager, "session_content")

        if not tab_manager or tab_manager.count() == 0:
            QMessageBox.warning(self, '导出失败', '没有可用的终端会话，请先打开一个终端会话。')
            return

        # 获取当前活动的终端实例
        current_tab = tab_manager.currentWidget()
        if not current_tab:
            return

        terminal = current_tab.findChild(Terminal)
        if not terminal:
            return

        # 获取预览内容并发送到终端
        content = self.preview_text.toPlainText()
        if content:
            terminal.bridge.sendData(content + '\n')
            QMessageBox.information(self, '导出成功', '内容已成功导出到终端！')
        else:
            QMessageBox.warning(self, '导出失败', '没有可导出的内容。')

    def export_to_file(self):
        """导出预览内容到文件"""
        # 获取预览内容
        content = self.preview_text.toPlainText()
        if not content:
            QMessageBox.warning(self, '导出失败', '没有可导出的内容。')
            return
            
        # 打开文件保存对话框
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            '保存文件',
            '',
            'Text Files (*.txt);;All Files (*)'
        )
        
        if not file_path:
            return
            
        try:
            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            QMessageBox.information(self, '导出成功', '内容已成功导出到文件！')
        except Exception as e:
            QMessageBox.critical(self, '导出失败', f'保存文件时发生错误：{str(e)}')